package org.dromara.sheet.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.sheet.constant.SplitType;
import org.dromara.sheet.domain.*;
import org.dromara.sheet.domain.dto.OssDto;
import org.dromara.sheet.domain.dto.platformForm.*;
import org.dromara.sheet.domain.dto.platformList.SearchButtonDto;
import org.dromara.sheet.domain.dto.platformList.SearchDataSourceDto;
import org.dromara.sheet.domain.vo.*;
import org.dromara.sheet.enums.FieldShowTypeEnum;
import org.dromara.sheet.enums.YesOrNoEnum;
import org.dromara.sheet.mapper.*;
import org.dromara.sheet.service.PlatformFormService;
import org.dromara.sheet.service.PlatformListService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 平台表单通用服务实现
 *
 * @author Ysl
 * @date 2023-09-18
 */
@RequiredArgsConstructor
@Service
public class PlatformFormServiceImpl implements PlatformFormService {

    private final PlatformListService platformListService;
    private final PlatformFormMapper platformFormMapper;
    private final SysSheetFormMapper sheetFormMapper;
    private final SysSheetFieldMapper sheetFieldMapper;
    private final SysSheetSearchMapper sheetSearchMapper;
    private final SysDataSourceMapper dataSourceMapper;
    private final SysSheetFormCheckMapper sheetFormCheckMapper;
    private final SysSheetMapper sysSheetMapper;
    private final SysSheetSelectMapper sheetSelectMapper;
    private final SysSheetFormAttachmentMapper sheetFormAttachmentMapper;
    private final SysSheetFormAuthMapper sheetFormAuthMapper;
    private final SysSheetFormFieldAuthMapper sheetFormFieldAuthMapper;


    /**
     * 获取表单详情
     *
     * @param sheetId 应用ID
     * @return
     */
    @Override
    public SheetFormInfoDto getSheetFormInfo(Long sheetId, Long orderId) throws Exception {

        // 应用表单
        List<SysSheetFormVo> sheetFormList = getSheetFormList(sheetId);

        // 获取应用字段
        List<SysSheetFieldVo> sheetFieldVoList = getSheetFieldList(sheetFormList);

        SheetFormInfoDto infoDto = new SheetFormInfoDto();
        // 页签
        infoDto.setTabList(getFormTab(sheetFormList));

        // 表单字段信息
        List<FormInfoDto> formInfoList = getFormFieldList(sheetFormList, sheetFieldVoList);
        infoDto.setFormInfoList(formInfoList);

        // 表单校验规则
        infoDto.setFormCheckList(getFormCheckList(sheetFormList));

        // 表单数据
        infoDto.setFormDataList(getFormData(sheetId, orderId, sheetFormList, sheetFieldVoList));

        return infoDto;
    }

    /**
     * 表单保存
     * @param formDto
     * @return
     */
    @Override
    public R<Long> postFormData(RequestFormDto formDto) throws Exception {
        // 获取表单
        List<SysSheetFormVo> sheetFormList = getSheetFormList(formDto.getSheetId());
        // 主表
        SysSheetFormVo masterForm = sheetFormList.stream().filter(form -> form.getPid() == 0).findFirst().orElse(null);
        // 子表
        List<SysSheetFormVo> childFormList = sheetFormList.stream().filter(form -> form.getPid()!= 0).toList();
        // 获取应用
        List<SysSheet> sheetList = sysSheetMapper.selectList(
            new LambdaQueryWrapper<SysSheet>().eq(SysSheet::getSheetId, formDto.getSheetId())
                .or().eq(SysSheet::getPid, formDto.getSheetId())
        );
        // 获取应用字段
        List<SysSheetFieldVo> sheetFieldList = getSheetFieldList(sheetFormList);

        // 主表数据
        SysSheet master = sheetList.stream().filter(sheet -> sheet.getSheetId().equals(masterForm.getSheetId())).findFirst().orElse(null);
        List<Long> longs = saveTableData(master, formDto.getMasterDataList(), sheetFieldList, formDto.getSelectDataList(), null, null);

        childFormList.forEach(child -> {
            SysSheetFormVo formVo = childFormList.stream().filter(item -> item.getSheetFormId().equals(child.getSheetFormId())).findFirst().orElse(null);
            SysSheet sheet = sheetList.stream().filter(item -> item.getSheetId().equals(formVo.getSheetId())).findFirst().orElse(null);
            List<Map<String, Object>> dataList = formDto.getChildDataList().stream().filter(item -> item.get("formId").equals(formVo.getSheetFormId().toString())).toList();
            saveTableData(sheet, dataList, sheetFieldList, formDto.getSelectDataList(), longs.get(0), sheet.getParentName());

            List<Map<String, Object>> delList = formDto.getChildDelList().stream().filter(item -> item.get("formId").equals(formVo.getSheetFormId().toString())).toList();
            delTableData(sheet, delList);
        });

        if (!formDto.getSelectDataList().isEmpty()){
            List<SysSheetSelect> list = MapstructUtils.convert(formDto.getSelectDataList(), SysSheetSelect.class);
            long count = list.stream().filter(item -> item.getOrderId() == null ).count();
            if (count == 0){
                sheetSelectMapper.insertBatch(list);
            }
        }
        return R.ok(longs.get(0));
    }

    /**
     * 表数据保存
     * @param sheet             应用
     * @param dataList          数据
     * @param sheetFieldList    字段
     * @param selectDataList    下拉数据
     * @param pid               主表ID
     * @param parentName        主表关联字段
     * @return
     */
    public List<Long> saveTableData(SysSheet sheet, List<Map<String, Object>> dataList, List<SysSheetFieldVo> sheetFieldList, List<SysSheetSelectVo> selectDataList, Long pid, String parentName){
        LoginUser loginUser = LoginHelper.getLoginUser();
        // 过滤表单启用字段
        List<SysSheetFieldVo> validFidldList = sheetFieldList.stream().filter(item ->item.getFormStatus().equals(YesOrNoEnum.YES.getCode())).toList();
        List<SysSheetFieldVo> fileList = validFidldList.stream().filter(item -> item.getShowType().equals(FieldShowTypeEnum.IMG_TYPE.getShowType()) || item.getShowType().equals(FieldShowTypeEnum.FILE_TYPE.getShowType())).toList();

        List<Map<String, Object>> saveList = new ArrayList<>();
        List<Map<String, Object>> updateList = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        List<SysSheetFormAttachment> attachmentList = new ArrayList<>();
        for (Map<String, Object> formData : dataList) {
            Long formId = Long.valueOf(formData.get("formId").toString());
            List<Map<String, Object>> fieldValue = (List<Map<String, Object>>) formData.get("fieldValue");
            if (fieldValue != null && fieldValue.size() > 0) {
                AtomicInteger index = new AtomicInteger();
                fieldValue.forEach(fieldList -> {

                    Object tableId = fieldList.get(sheet.getTableId());
                    long id = IdWorker.getId();
                    if (tableId == null){
                        fieldList.put(sheet.getTableId(), id);
                        fieldList.put("sheet_id", sheet.getSheetId());
                        fieldList.put("tenant_id", loginUser.getTenantId());
                        fieldList.put("create_dept", loginUser.getDeptId());
                        fieldList.put("create_by", loginUser.getUserId());
                        fieldList.put("create_time", new Date());
                    } else {
                        id = Long.parseLong(tableId.toString());

                        fieldList.put("update_by", loginUser.getUserId());
                        fieldList.put("update_time", new Date());
                    }
                    ids.add(id);
                    if (pid != null){
                        fieldList.put(parentName, pid);
                    }

                    Map<String, Object> map = new HashMap<>();
                    fieldList.forEach((key,value) -> {
                        long count = validFidldList.stream().filter(field -> field.getSheetId().equals(sheet.getSheetId()) && field.getFieldName().equals(key) && !FieldShowTypeEnum.getAllSelectType().contains(field.getShowType())).count();
                        if (count > 0){
                            map.put(key, value);
                        }
                    });
                    if (!map.isEmpty() && tableId == null){
                        saveList.add(map);
                    } else if (!map.isEmpty()){
                        updateList.add(map);
                    }

                    Long finalId = id;
                    selectDataList.forEach(item -> {
                        if (item.getFormId().equals(formId) && item.getIndex() == index.get()){
                            item.setOrderId(finalId);
                        }
                    });
                    index.getAndIncrement();

                    // 处理文件
                    for (SysSheetFieldVo fileField : fileList) {
                        if (fieldList.containsKey(fileField.getFieldName()) && fileField.getSheetId().equals(sheet.getSheetId())){
                            Object ossId = fieldList.get(fileField.getFieldName());
                            if (ossId != null){
                                String[] split = ossId.toString().split(SplitType.SPLIT_COMMA);
                                for (String str : split) {
                                    SysSheetFormAttachment attachment = new SysSheetFormAttachment();
                                    attachment.setSheetId(sheet.getSheetId());
                                    attachment.setOrderId(id);
                                    attachment.setFieldId(fileField.getSheetFieldId());
                                    attachment.setOssId(Long.valueOf(str));
                                    attachmentList.add(attachment);
                                }
                            }

                        }
                    }
                });
            }

            if (!saveList.isEmpty()){
                Map<String, Object> columnMap2 = new HashMap<>();
                columnMap2.put("tableName", sheet.getTableName());
                // 字段数据
                columnMap2.put("columnMap", saveList.get(0));
                // 数据列表
                columnMap2.put("mapList", saveList);
                platformFormMapper.saveTableData(columnMap2);
            }
           if (!updateList.isEmpty()){
               Map<String, Object> columnMap2 = new HashMap<>();
               columnMap2.put("tableName", sheet.getTableName());
               columnMap2.put("tableId", sheet.getTableId());
               columnMap2.put("columnMap", updateList.get(0));
               columnMap2.put("mapList", updateList);
               platformFormMapper.updateTableData(columnMap2);
           }
        }

        sheetSelectMapper.delete(
            new LambdaQueryWrapper<SysSheetSelect>().in(SysSheetSelect::getOrderId, ids)
        );

        sheetFormAttachmentMapper.delete(
            new LambdaQueryWrapper<SysSheetFormAttachment>().in(SysSheetFormAttachment::getOrderId, ids)
        );

        if (!attachmentList.isEmpty()){
            List<Long> ossIdList = attachmentList.stream().map(SysSheetFormAttachment::getOssId).toList();
            List<OssDto> ossList = platformFormMapper.getOssList(ossIdList);
            for (SysSheetFormAttachment attachment : attachmentList) {
                OssDto ossDto = ossList.stream().filter(item -> item.getOssId().equals(attachment.getOssId())).findFirst().orElse(new OssDto());
                attachment.setUrl(ossDto.getUrl());
                attachment.setFileName(ossDto.getFileName());
                attachment.setFileSuffix(ossDto.getFileSuffix());
                attachment.setOriginalName(ossDto.getOriginalName());
            }
            sheetFormAttachmentMapper.insertBatch(attachmentList);
        }

        return ids;
    }

    /**
     * 删除表单数据（逻辑删除）
     * @param sheet
     * @param delList
     */
    private void delTableData(SysSheet sheet, List<Map<String, Object>> delList) {
        if (!delList.isEmpty()){
            List<Object> ids = new ArrayList<>();
            for (Map<String, Object> formData : delList) {
                LinkedHashMap<String, Object> fieldValue = (LinkedHashMap<String, Object>) formData.get("fieldValue");
                if (fieldValue != null){
                    Object tableId = fieldValue.get(sheet.getTableId());
                    ids.add(tableId);
                }
            }
            Map<String,Object> params = new HashMap<>();
            params.put("tableName", sheet.getTableName());
            params.put("tableId", sheet.getTableId());
            params.put("idList", ids);
            platformFormMapper.delTableData(params);
        }
    }

    /**
     * 获取表单
     *
     * @param sheetId 应用ID
     * @return
     */
    public List<SysSheetFormVo> getSheetFormList(Long sheetId) throws Exception {

        List<SysSheetFormAuthVo> formAuthList = new ArrayList<>();
        if (!LoginHelper.isSuperAdmin()){
            List<RoleDTO> roles = LoginHelper.getLoginUser().getRoles();
            if (roles.size() > 0){
                formAuthList = sheetFormAuthMapper.selectVoList(
                    new LambdaQueryWrapper<SysSheetFormAuth>()
                        .in(SysSheetFormAuth::getRoleId, roles.stream().map(RoleDTO::getRoleId).toList())
                );
            }
            if (formAuthList.isEmpty()) {
                throw new Exception("请先表单授权！");
            }
        }

        // 主表单
        SysSheetFormVo sysSheetFormVo = sheetFormMapper.selectVoOne(
            new LambdaQueryWrapper<SysSheetForm>().eq(SysSheetForm::getSheetId, sheetId).eq(SysSheetForm::getStatus, YesOrNoEnum.YES.getCode())
                .in(!LoginHelper.isSuperAdmin(),SysSheetForm::getSheetFormId, formAuthList.stream().map(SysSheetFormAuthVo::getFormId).toList())
        );
        if (sysSheetFormVo == null) {
            throw new Exception("请检查是否有配置主表单或授权！");
        } else {
            if (StringUtils.isEmpty(sysSheetFormVo.getTabName())) {
                sysSheetFormVo.setTabName(sysSheetFormVo.getName());
            }
        }
        // 子表单
        List<SysSheetFormVo> children = sheetFormMapper.selectVoList(
            new LambdaQueryWrapper<SysSheetForm>().eq(SysSheetForm::getStatus, YesOrNoEnum.YES.getCode())
                .in(!LoginHelper.isSuperAdmin(),SysSheetForm::getSheetFormId, formAuthList.stream().map(SysSheetFormAuthVo::getFormId).toList())
                .apply(DataBaseHelper.findInSet(sysSheetFormVo.getSheetFormId(), "path"))
        );
        List<SysSheetFormVo> list = new ArrayList<>();
        list.add(sysSheetFormVo);
        list.addAll(children);

        return list.stream().sorted((Comparator.comparing(SysSheetFormVo::getSort))).toList();
    }

    /**
     * 获取表单页签
     *
     * @param sheetFormList 表单数据
     * @return
     */
    public List<TabDto> getFormTab(List<SysSheetFormVo> sheetFormList) {
        // 获取有多少页签
        List<String> tabList = sheetFormList.stream().map(SysSheetFormVo::getTabName).filter(StringUtils::isNotEmpty).distinct().toList();

        List<SysSheetFormVo> haveTabList = sheetFormList.stream().filter(item -> StringUtils.isNotEmpty(item.getTabName())).toList();
        List<SysSheetFormVo> noTabList = sheetFormList.stream().filter(item -> StringUtils.isEmpty(item.getTabName())).toList();
        List<Long> ids = noTabList.stream().map(SysSheetFormVo::getSheetFormId).toList();

        // 组装页签数据
        List<TabDto> list = new ArrayList<>();
        tabList.forEach(item -> {
            TabDto dto = new TabDto();
            List<Long> formIds = haveTabList.stream().filter(sheetForm -> sheetForm.getTabName().equals(item)).map(SysSheetFormVo::getSheetFormId).toList();
            dto.setTabName(item);
            dto.setFormIdList(formIds);
            list.add(dto);
        });

        // 将为设置页签的表单赋给主表单
        SysSheetFormVo sysSheetFormVo = sheetFormList.stream().filter(item -> item.getPid().equals(0L)).findFirst().orElse(null);
        list.forEach(dto -> {
            if (sysSheetFormVo != null && dto.getTabName().equals(sysSheetFormVo.getTabName())) {
                List<Long> formIds = new ArrayList<>(dto.getFormIdList());
                if (ids.size() > 0) {
                    formIds.addAll(ids);
                }
                dto.setFormIdList(formIds);
            }
        });

        return list;
    }

    /**
     * 获取表单字段信息
     *
     * @param sheetFormList 表单数据
     * @param sheetFieldVoList 字段信息
     * @return key: 表单ID， value: 字段信息
     */
    public List<FormInfoDto> getFormFieldList(List<SysSheetFormVo> sheetFormList, List<SysSheetFieldVo> sheetFieldVoList) {

        // 实体转化，补全信息
        List<FormFieldDto> fieldDtoList = StreamUtils.toList(sheetFieldVoList, item -> {
            FormFieldDto dto = JSONUtil.toBean(JSONUtil.toJsonStr(item), FormFieldDto.class);
            if (StringUtils.isEmpty(dto.getFieldGroup())) {
                dto.setFieldGroup("基本信息");
            }
            return dto;
        });

        // 组装表单信息
        List<FormInfoDto> infoDtoList = new ArrayList<>();

        List<Long> sheetIds = sheetFormList.stream().map(SysSheetFormVo::getSheetId).toList();

        // 获取应用
        List<SysSheetVo> sheetList = sysSheetMapper.selectVoList(
            new LambdaQueryWrapper<SysSheet>().in(SysSheet::getSheetId, sheetIds)
        );

        sheetFormList.forEach(sheetForm -> {
            List<String> groupList = new ArrayList<>();
            List<FormFieldDto> list = fieldDtoList.stream().filter(fieldDto -> fieldDto.getSheetId().equals(sheetForm.getSheetId())).sorted(Comparator.comparing(FormFieldDto::getFormSort)).toList();
            // 设置数据源
            list.forEach(item -> {
                if (item.getDataSourceId() != null) {
                    List<SearchDataSourceDto> dataList = new ArrayList<>();
                    if (item.getDataSourceType() == 1) {
                        // 数据字典
                        dataList = sheetSearchMapper.getDictDataList(item.getDataSourceId());
                    } else {
                        // 自定义数据源
                        SysDataSourceVo dataSource = dataSourceMapper.getDataSourceBySheetSourceId(item.getDataSourceId());
                        if (dataSource != null) {
                            dataList = sheetSearchMapper.getDiyDataSourceList(dataSource);
                        }
                    }
                    item.setSourceList(dataList);
                    if (FieldShowTypeEnum.getTreeSelectType().contains(item.getShowType())){
                        SearchDataSourceDto dataSourceDto = new SearchDataSourceDto();
                        List<SearchDataSourceDto> list1 = dataSourceDto.builTree(dataList);
                        item.setSourceList(list1);
                    }
                }
            });

            // 表单字段分组数据
            List<FormInfoGroupDto> dtoList = new ArrayList<>();

            // 字段分组按表单字段升序规则设置
            list.forEach(item -> {
                if (!groupList.contains(item.getFieldGroup())){
                    groupList.add(item.getFieldGroup());

                    FormInfoGroupDto infoDto = new FormInfoGroupDto();
                    infoDto.setGroupName(item.getFieldGroup());
                    dtoList.add(infoDto);
                }
            });

            // 字段分组
            Map<String, List<FormFieldDto>> groupMap = list.stream().collect(Collectors.groupingBy(FormFieldDto::getFieldGroup));
            groupMap.forEach((key, value) -> {
                dtoList.forEach(item -> {
                    if (item.getGroupName().equals(key)){
                        item.setFormFieldList(value);
                    }
                });
            });

            // TODO 待优化
            List<SearchButtonDto> searchButtonList = platformListService.getSheetButtonConfig(sheetForm.getSheetFormId());

            FormInfoDto infoDto = new FormInfoDto();
            infoDto.setFormId(sheetForm.getSheetFormId());
            infoDto.setShowType(sheetForm.getShowType());
            infoDto.setIsChild(sheetForm.getPid().compareTo(0L));
            String formName = StringUtils.isEmpty(sheetForm.getShowName()) ? sheetForm.getName() : sheetForm.getShowName();
            infoDto.setFormName(formName);
            infoDto.setGroupList(dtoList);
            infoDto.setButtonList(searchButtonList);
            infoDto.setSheet(sheetList.stream().filter(item -> item.getSheetId().equals(sheetForm.getSheetId())).findFirst().orElse(null));
            infoDtoList.add(infoDto);
        });

        return infoDtoList;
    }

    /**
     * 获取表单数据
     * @param sheetFormList 表单数据
     * @return key: 表单ID， value: 数据
     */
    public List<FormDataDto> getFormData(Long sheetId, Long orderId, List<SysSheetFormVo> sheetFormList, List<SysSheetFieldVo> sheetFieldVoList){
        List<FormDataDto> dataDtoList = new ArrayList<>();

        // 获取应用
        List<SysSheet> sheetList = sysSheetMapper.selectList(
            new LambdaQueryWrapper<SysSheet>().eq(SysSheet::getSheetId, sheetId)
                .or().eq(SysSheet::getPid, sheetId)
        );

        List<SysSheetSelectVo> selectList;
        // 获取表单数据
        Map<Long, List<Map<String, Object>>> map = new HashMap<>();
        List<Object> ids = new ArrayList<>();
        if (orderId != null){
            sheetList.forEach(sheet -> {
                String fields = sheetFieldVoList.stream().filter(field -> field.getSheetId().equals(sheet.getSheetId()) && field.getFormStatus().equals(YesOrNoEnum.YES.getCode())).map(SysSheetFieldVo::getFieldName).collect(Collectors.joining(SplitType.SPLIT_COMMA));
                Map<String,Object> params = new HashMap<>();
                params.put("tableName", sheet.getTableName());
                params.put("tableId", sheet.getTableId());
                params.put("orderId", orderId);
                params.put("sheetId", sheet.getSheetId());
                params.put("fields", fields);
                if (sheet.getPid().equals(0L)){
                    params.put("master", "true");
                }
                List<Map<String, Object>> resultMap = platformFormMapper.getTableDataMap(params);
                resultMap.forEach(item -> {
                   ids.add(item.get(sheet.getTableId()));
                });
                map.put(sheet.getSheetId(), resultMap);
            });

            // 获取下拉想数据
            selectList = sheetSelectMapper.selectVoList(
                new LambdaQueryWrapper<SysSheetSelect>().in(SysSheetSelect::getOrderId, ids)
            );
        } else {
            selectList = new ArrayList<>();
        }


        sheetFormList.forEach(form -> {
            FormDataDto dataDto = new FormDataDto();

            SysSheet sysSheet = sheetList.stream().filter(item -> item.getSheetId().equals(form.getSheetId())).findFirst().orElse(null);

            List<SysSheetFieldVo> formFieldList = sheetFieldVoList.stream().filter(item -> item.getSheetId().equals(form.getSheetId())).toList();
            List<Map<String, Object>> formDataList = map.get(form.getSheetId());
            // 组装后的数据
            List<Map<String, Object>> listMap = new ArrayList<>();

            if (formDataList!= null &&!formDataList.isEmpty()){

                for (Map<String, Object> formMap : formDataList) {
                    Map<String, Object> dataMap = new HashMap<>();
                    formFieldList.forEach(field -> {
                        if (formMap.containsKey(field.getFieldName())){
                            dataMap.put(field.getFieldName(), formMap.get(field.getFieldName()));

                            // 设置选择项值
                            if (FieldShowTypeEnum.getAllSelectType().contains(field.getShowType())){
                                List<SysSheetSelectVo> collect = selectList.stream().filter(item -> item.getSheetId().equals(form.getSheetId()) &&
                                    item.getFieldId().equals(field.getSheetFieldId()) && item.getOrderId().equals(formMap.get(sysSheet.getTableId()))).toList();
                                List<String> showPathList = collect.stream().map(SysSheetSelectVo::getShowPath).toList();
                                // 单选
                                if (field.getShowType().equals(FieldShowTypeEnum.SINGLE.getShowType()) || field.getShowType().equals(FieldShowTypeEnum.TREE_SINGLE.getShowType())){
                                    dataMap.put(field.getFieldName(), showPathList.stream().collect(Collectors.joining()));
                                } else if (field.getShowType().equals(FieldShowTypeEnum.CASCADE_SINGLE.getShowType()) || field.getShowType().equals(FieldShowTypeEnum.CASCADE_MULTIPLE.getShowType())){
                                    List<String> list = new ArrayList<>();
                                    showPathList.forEach(item -> {
                                        String[] split = item.split(SplitType.SPLIT_COMMA);
                                        if (split.length > 0){
                                            list.addAll(Arrays.asList(split));
                                        }
                                    });
                                    dataMap.put(field.getFieldName(), list);
                                } else {
                                    dataMap.put(field.getFieldName(), showPathList);
                                }
                            }
                        }
                    });
                    listMap.add(dataMap);
                }

            } else {
                Map<String, Object> dataMap = new HashMap<>();
                formFieldList.forEach(field -> {
                    if (FieldShowTypeEnum.getTreeSelectType().contains(field.getShowType())){
                        dataMap.put(field.getFieldName(), "");
                    } else {
                        dataMap.put(field.getFieldName(), null);
                    }
                });
                listMap.add(dataMap);
            }

            dataDto.setFormId(form.getSheetFormId());

            dataDto.setFieldValue(listMap);
            dataDtoList.add(dataDto);
        });

        return dataDtoList;
    }

    /**
     * 获取应用字段
     * @param sheetFormList 表单数据
     * @return
     */
    public List<SysSheetFieldVo> getSheetFieldList(List<SysSheetFormVo> sheetFormList){
        List<SysSheetFieldVo> sheetFieldList = sheetFieldMapper.selectVoList(
            new LambdaQueryWrapper<SysSheetField>().eq(SysSheetField::getFormStatus ,YesOrNoEnum.YES.getCode())
                .in(SysSheetField::getSheetId, sheetFormList.stream().map(SysSheetFormVo::getSheetId).toList())
                .orderByAsc(SysSheetField::getFormSort)
        );

        // 获取授权字段
        List<SysSheetFormFieldAuthVo> formFieldAuthList = new ArrayList<>();

        List<SysSheetFieldVo> filterFieldList = new ArrayList<>();
        if (!LoginHelper.isSuperAdmin()){
            List<RoleDTO> roles = LoginHelper.getLoginUser().getRoles();
            if (roles.size() > 0){
                formFieldAuthList = sheetFormFieldAuthMapper.selectVoList(
                    new LambdaQueryWrapper<SysSheetFormFieldAuth>().in(SysSheetFormFieldAuth::getRoleId, roles.stream().map(RoleDTO::getRoleId).toList())
                        .in(SysSheetFormFieldAuth::getFormId, sheetFormList.stream().map(SysSheetFormVo::getSheetFormId).toList())
                );
            }

            List<SysSheetFormFieldAuthVo> finalFormFieldAuthList = formFieldAuthList;
            filterFieldList = sheetFieldList.stream().filter(item -> finalFormFieldAuthList.stream().map(SysSheetFormFieldAuthVo::getFieldId).toList().contains(item.getSheetFieldId())).toList();
            filterFieldList.forEach(item -> {
                finalFormFieldAuthList.forEach(auth -> {
                    if (item.getSheetFieldId().equals(auth.getFieldId())){
                        item.setIsAuth(auth.getIsAuth());
                        item.setIsHidden(StringUtils.isNotEmpty(auth.getIsHidden())?auth.getIsHidden():YesOrNoEnum.NO.getCode());
                        item.setIsEdit(StringUtils.isNotEmpty(auth.getIsEdit())?auth.getIsEdit():YesOrNoEnum.NO.getCode());
                    }
                });
            });
        } else {
            filterFieldList = sheetFieldList;
            filterFieldList.forEach(item -> {
                item.setIsAuth(YesOrNoEnum.YES.getCode());
                item.setIsHidden(item.getShowForm().equals(YesOrNoEnum.YES.getCode()) ? YesOrNoEnum.NO.getCode() : YesOrNoEnum.YES.getCode());
                item.setIsEdit(YesOrNoEnum.YES.getCode());
            });
        }

        return filterFieldList;
    }

    /**
     * 获取表单校验规则
     * @param sheetFormList
     * @return
     */
    public List<FormCheckDto> getFormCheckList(List<SysSheetFormVo> sheetFormList) {

        List<Long> fromIds = sheetFormList.stream().map(SysSheetFormVo::getSheetFormId).toList();

        // 获取表单校验规则
        List<SysSheetFormCheckVo> checkList = sheetFormCheckMapper.selectVoList(
            new LambdaQueryWrapper<SysSheetFormCheck>().in(SysSheetFormCheck::getFormId, fromIds)
        );

        // 按表单分组
        Map<Long, List<SysSheetFormCheckVo>> groupMap = checkList.stream().collect(Collectors.groupingBy(SysSheetFormCheckVo::getFormId));

        List<FormCheckDto> formCheckList = new ArrayList<>();
        groupMap.forEach((key, value) -> {
            // 按字段分组
            Map<String, List<SysSheetFormCheckVo>> fieldMap = value.stream().filter(item -> item.getFormId().equals(key)).collect(Collectors.groupingBy(SysSheetFormCheckVo::getSheetField));

            List<FormCheckFieldDto> checkDtoList = new ArrayList<>();
            fieldMap.forEach((field, fieldValue) -> {
                FormCheckFieldDto dto = new FormCheckFieldDto();
                dto.setFieldName(field);
                dto.setCheckRuleList(fieldValue);
                checkDtoList.add(dto);
            });

            FormCheckDto checkDto = new FormCheckDto();
            checkDto.setFormId(key);
            checkDto.setFieldList(checkDtoList);
            formCheckList.add(checkDto);
        });

        return formCheckList;
    }
}
